2 // phpcs:ignoreFile -- It's an external lib and it isn't. Let's not bother.
4 * Memcached client for PHP.
6 * +---------------------------------------------------------------------------+
7 * | memcached client, PHP |
8 * +---------------------------------------------------------------------------+
9 * | Copyright (c) 2003 Ryan T. Dean <rtdean@cytherianage.net> |
10 * | All rights reserved. |
12 * | Redistribution and use in source and binary forms, with or without |
13 * | modification, are permitted provided that the following conditions |
16 * | 1. Redistributions of source code must retain the above copyright |
17 * | notice, this list of conditions and the following disclaimer. |
18 * | 2. Redistributions in binary form must reproduce the above copyright |
19 * | notice, this list of conditions and the following disclaimer in the |
20 * | documentation and/or other materials provided with the distribution. |
22 * | THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR |
23 * | IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES |
24 * | OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. |
25 * | IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, |
26 * | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT |
27 * | NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
28 * | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
29 * | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
30 * | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF |
31 * | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
32 * +---------------------------------------------------------------------------+
33 * | Author: Ryan T. Dean <rtdean@cytherianage.net> |
34 * | Heavily influenced by the Perl memcached client by Brad Fitzpatrick. |
35 * | Permission granted by Brad Fitzpatrick for relicense of ported Perl |
36 * | client logic under 2-clause BSD license. |
37 * +---------------------------------------------------------------------------+
44 * This is a PHP client for memcached - a distributed memory cache daemon.
46 * More information is available at http://www.danga.com/memcached/
50 * $mc = new MemcachedClient(array(
53 * array( '192.0.0.1:10010', 2 ),
57 * 'compress_threshold' => 10240,
58 * 'persistent' => true
61 * $mc->add( 'key', array( 'some', 'array' ) );
62 * $mc->replace( 'key', 'some random string' );
63 * $val = $mc->get( 'key' );
65 * @author Ryan T. Dean <rtdean@cytherianage.net>
69 use Psr\Log\LoggerInterface
;
70 use Psr\Log\NullLogger
;
72 // {{{ class MemcachedClient
74 * memcached client class implemented using (p)fsockopen()
76 * @author Ryan T. Dean <rtdean@cytherianage.net>
79 class MemcachedClient
{
87 * Flag: indicates data is serialized
92 * Flag: indicates data is compressed
97 * Flag: indicates data is an integer
104 * Minimum savings to store data compressed
106 const COMPRESSION_SAVINGS
= 0.20;
122 * Cached Sockets that are connected
130 * Current debug status; 0 - none to 9 - profiling
138 * Dead hosts, assoc array, 'host'=>'unixtime when ok to check again'
146 * Is compression available?
154 * Do we want to use compression?
159 public $_compress_enable;
162 * At how many bytes should we compress?
167 public $_compress_threshold;
170 * Are we using persistent links?
178 * If only using one server; contains ip:port to connect to
183 public $_single_sock;
186 * Array containing ip:port or array(ip:port, weight)
202 * Total # of bit buckets we have
207 public $_bucketcount;
210 * # of total servers we have
218 * Stream timeout in seconds. Applies for example to fread()
223 public $_timeout_seconds;
226 * Stream timeout in microseconds
231 public $_timeout_microseconds;
234 * Connect timeout in seconds
236 public $_connect_timeout;
239 * Number of connection attempts for each server
241 public $_connect_attempts;
244 * @var LoggerInterface
251 // {{{ public functions
255 * Memcache initializer
257 * @param array $args Associative array of settings
259 public function __construct( $args ) {
260 $this->set_servers( $args['servers'] ??
array() );
261 $this->_debug
= $args['debug'] ??
false;
262 $this->stats
= array();
263 $this->_compress_threshold
= $args['compress_threshold'] ??
0;
264 $this->_persistent
= $args['persistent'] ??
false;
265 $this->_compress_enable
= true;
266 $this->_have_zlib
= function_exists( 'gzcompress' );
268 $this->_cache_sock
= array();
269 $this->_host_dead
= array();
271 $this->_timeout_seconds
= 0;
272 $this->_timeout_microseconds
= $args['timeout'] ??
500000;
274 $this->_connect_timeout
= $args['connect_timeout'] ??
0.1;
275 $this->_connect_attempts
= 2;
277 $this->_logger
= $args['logger'] ??
new NullLogger();
283 * @param mixed $value
284 * @return string|integer
286 public function serialize( $value ) {
287 return serialize( $value );
291 * @param string $value
294 public function unserialize( $value ) {
295 return unserialize( $value );
301 * Adds a key/value to the memcache server if one isn't already set with
304 * @param string $key Key to set with data
305 * @param mixed $val Value to store
306 * @param int $exp (optional) Expiration time. This can be a number of seconds
307 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
308 * longer must be the timestamp of the time at which the mapping should expire. It
309 * is safe to use timestamps in all cases, regardless of expiration
310 * eg: strtotime("+3 hour")
314 public function add( $key, $val, $exp = 0 ) {
315 return $this->_set( 'add', $key, $val, $exp );
322 * Decrease a value stored on the memcache server
324 * @param string $key Key to decrease
325 * @param int $amt (optional) amount to decrease
327 * @return mixed False on failure, value on success
329 public function decr( $key, $amt = 1 ) {
330 return $this->_incrdecr( 'decr', $key, $amt );
337 * Deletes a key from the server, optionally after $time
339 * @param string $key Key to delete
340 * @param int $time (optional) how long to wait before deleting
342 * @return bool True on success, false on failure
344 public function delete( $key, $time = 0 ) {
345 if ( !$this->_active
) {
349 $sock = $this->get_sock( $key );
350 if ( !is_resource( $sock ) ) {
354 $key = is_array( $key ) ?
$key[1] : $key;
356 if ( isset( $this->stats
['delete'] ) ) {
357 $this->stats
['delete']++
;
359 $this->stats
['delete'] = 1;
361 $cmd = "delete $key $time\r\n";
362 if ( !$this->_fwrite( $sock, $cmd ) ) {
365 $res = $this->_fgets( $sock );
367 if ( $this->_debug
) {
368 $this->_debugprint( sprintf( "MemCache: delete %s (%s)", $key, $res ) );
371 if ( $res == "DELETED" ||
$res == "NOT_FOUND" ) {
379 * Changes the TTL on a key from the server to $time
382 * @param int $time TTL in seconds
384 * @return bool True on success, false on failure
386 public function touch( $key, $time = 0 ) {
387 if ( !$this->_active
) {
391 $sock = $this->get_sock( $key );
392 if ( !is_resource( $sock ) ) {
396 $key = is_array( $key ) ?
$key[1] : $key;
398 if ( isset( $this->stats
['touch'] ) ) {
399 $this->stats
['touch']++
;
401 $this->stats
['touch'] = 1;
403 $cmd = "touch $key $time\r\n";
404 if ( !$this->_fwrite( $sock, $cmd ) ) {
407 $res = $this->_fgets( $sock );
409 if ( $this->_debug
) {
410 $this->_debugprint( sprintf( "MemCache: touch %s (%s)", $key, $res ) );
413 if ( $res == "TOUCHED" ) {
422 * @param int $timeout
425 public function lock( $key, $timeout = 0 ) {
434 public function unlock( $key ) {
440 // {{{ disconnect_all()
443 * Disconnects all connected sockets
445 public function disconnect_all() {
446 foreach ( $this->_cache_sock
as $sock ) {
450 $this->_cache_sock
= array();
454 // {{{ enable_compress()
457 * Enable / Disable compression
459 * @param bool $enable True to enable, false to disable
461 public function enable_compress( $enable ) {
462 $this->_compress_enable
= $enable;
466 // {{{ forget_dead_hosts()
469 * Forget about all of the dead hosts
471 public function forget_dead_hosts() {
472 $this->_host_dead
= array();
479 * Retrieves the value associated with the key from the memcache server
481 * @param array|string $key key to retrieve
482 * @param float $casToken [optional]
486 public function get( $key, &$casToken = null ) {
487 if ( $this->_debug
) {
488 $this->_debugprint( "get($key)" );
491 if ( !is_array( $key ) && strval( $key ) === '' ) {
492 $this->_debugprint( "Skipping key which equals to an empty string" );
496 if ( !$this->_active
) {
500 $sock = $this->get_sock( $key );
502 if ( !is_resource( $sock ) ) {
506 $key = is_array( $key ) ?
$key[1] : $key;
507 if ( isset( $this->stats
['get'] ) ) {
508 $this->stats
['get']++
;
510 $this->stats
['get'] = 1;
513 $cmd = "gets $key\r\n";
514 if ( !$this->_fwrite( $sock, $cmd ) ) {
519 $this->_load_items( $sock, $val, $casToken );
521 if ( $this->_debug
) {
522 foreach ( $val as $k => $v ) {
524 sprintf( "MemCache: sock %s got %s", $this->serialize( $sock ), $k ) );
529 if ( isset( $val[$key] ) ) {
539 * Get multiple keys from the server(s)
541 * @param array $keys Keys to retrieve
545 public function get_multi( $keys ) {
546 if ( !$this->_active
) {
550 if ( isset( $this->stats
['get_multi'] ) ) {
551 $this->stats
['get_multi']++
;
553 $this->stats
['get_multi'] = 1;
555 $sock_keys = array();
557 foreach ( $keys as $key ) {
558 $sock = $this->get_sock( $key );
559 if ( !is_resource( $sock ) ) {
562 $key = is_array( $key ) ?
$key[1] : $key;
563 if ( !isset( $sock_keys[$sock] ) ) {
564 $sock_keys[intval( $sock )] = array();
567 $sock_keys[intval( $sock )][] = $key;
571 // Send out the requests
572 foreach ( $socks as $sock ) {
574 foreach ( $sock_keys[intval( $sock )] as $key ) {
579 if ( $this->_fwrite( $sock, $cmd ) ) {
586 foreach ( $gather as $sock ) {
587 $this->_load_items( $sock, $val, $casToken );
590 if ( $this->_debug
) {
591 foreach ( $val as $k => $v ) {
592 $this->_debugprint( sprintf( "MemCache: got %s", $k ) );
603 * Increments $key (optionally) by $amt
605 * @param string $key Key to increment
606 * @param int $amt (optional) amount to increment
608 * @return int|null Null if the key does not exist yet (this does NOT
609 * create new mappings if the key does not exist). If the key does
610 * exist, this returns the new value for that key.
612 public function incr( $key, $amt = 1 ) {
613 return $this->_incrdecr( 'incr', $key, $amt );
620 * Overwrites an existing value for key; only works if key is already set
622 * @param string $key Key to set value as
623 * @param mixed $value Value to store
624 * @param int $exp (optional) Expiration time. This can be a number of seconds
625 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
626 * longer must be the timestamp of the time at which the mapping should expire. It
627 * is safe to use timestamps in all cases, regardless of exipration
628 * eg: strtotime("+3 hour")
632 public function replace( $key, $value, $exp = 0 ) {
633 return $this->_set( 'replace', $key, $value, $exp );
640 * Passes through $cmd to the memcache server connected by $sock; returns
641 * output as an array (null array if no output)
643 * @param Resource $sock Socket to send command on
644 * @param string $cmd Command to run
646 * @return array Output array
648 public function run_command( $sock, $cmd ) {
649 if ( !is_resource( $sock ) ) {
653 if ( !$this->_fwrite( $sock, $cmd ) ) {
659 $res = $this->_fgets( $sock );
661 if ( preg_match( '/^END/', $res ) ) {
664 if ( strlen( $res ) == 0 ) {
675 * Unconditionally sets a key to a given value in the memcache. Returns true
676 * if set successfully.
678 * @param string $key Key to set value as
679 * @param mixed $value Value to set
680 * @param int $exp (optional) Expiration time. This can be a number of seconds
681 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
682 * longer must be the timestamp of the time at which the mapping should expire. It
683 * is safe to use timestamps in all cases, regardless of exipration
684 * eg: strtotime("+3 hour")
686 * @return bool True on success
688 public function set( $key, $value, $exp = 0 ) {
689 return $this->_set( 'set', $key, $value, $exp );
696 * Sets a key to a given value in the memcache if the current value still corresponds
697 * to a known, given value. Returns true if set successfully.
699 * @param float $casToken Current known value
700 * @param string $key Key to set value as
701 * @param mixed $value Value to set
702 * @param int $exp (optional) Expiration time. This can be a number of seconds
703 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
704 * longer must be the timestamp of the time at which the mapping should expire. It
705 * is safe to use timestamps in all cases, regardless of exipration
706 * eg: strtotime("+3 hour")
708 * @return bool True on success
710 public function cas( $casToken, $key, $value, $exp = 0 ) {
711 return $this->_set( 'cas', $key, $value, $exp, $casToken );
715 // {{{ set_compress_threshold()
718 * Set the compression threshold
720 * @param int $thresh Threshold to compress if larger than
722 public function set_compress_threshold( $thresh ) {
723 $this->_compress_threshold
= $thresh;
733 * @param bool $dbg True for debugging, false otherwise
735 public function set_debug( $dbg ) {
736 $this->_debug
= $dbg;
743 * Set the server list to distribute key gets and puts between
746 * @param array $list Array of servers to connect to
748 public function set_servers( $list ) {
749 $this->_servers
= $list;
750 $this->_active
= count( $list );
751 $this->_buckets
= null;
752 $this->_bucketcount
= 0;
754 $this->_single_sock
= null;
755 if ( $this->_active
== 1 ) {
756 $this->_single_sock
= $this->_servers
[0];
761 * Sets the timeout for new connections
763 * @param int $seconds Number of seconds
764 * @param int $microseconds Number of microseconds
766 public function set_timeout( $seconds, $microseconds ) {
767 $this->_timeout_seconds
= $seconds;
768 $this->_timeout_microseconds
= $microseconds;
773 // {{{ private methods
777 * Close the specified socket
779 * @param string $sock Socket to close
783 function _close_sock( $sock ) {
784 $host = array_search( $sock, $this->_cache_sock
);
785 fclose( $this->_cache_sock
[$host] );
786 unset( $this->_cache_sock
[$host] );
790 // {{{ _connect_sock()
793 * Connects $sock to $host, timing out after $timeout
795 * @param int $sock Socket to connect
796 * @param string $host Host:IP to connect to
801 function _connect_sock( &$sock, $host ) {
802 list( $ip, $port ) = preg_split( '/:(?=\d)/', $host );
804 $timeout = $this->_connect_timeout
;
805 $errno = $errstr = null;
806 for ( $i = 0; !$sock && $i < $this->_connect_attempts
; $i++
) {
807 Wikimedia\
suppressWarnings();
808 if ( $this->_persistent
== 1 ) {
809 $sock = pfsockopen( $ip, $port, $errno, $errstr, $timeout );
811 $sock = fsockopen( $ip, $port, $errno, $errstr, $timeout );
813 Wikimedia\restoreWarnings
();
816 $this->_error_log( "Error connecting to $host: $errstr" );
817 $this->_dead_host( $host );
821 // Initialise timeout
822 stream_set_timeout( $sock, $this->_timeout_seconds
, $this->_timeout_microseconds
);
824 // If the connection was persistent, flush the read buffer in case there
825 // was a previous incomplete request on this connection
826 if ( $this->_persistent
) {
827 $this->_flush_read_buffer( $sock );
836 * Marks a host as dead until 30-40 seconds in the future
838 * @param string $sock Socket to mark as dead
842 function _dead_sock( $sock ) {
843 $host = array_search( $sock, $this->_cache_sock
);
844 $this->_dead_host( $host );
848 * @param string $host
850 function _dead_host( $host ) {
851 $ip = explode( ':', $host )[0];
852 $this->_host_dead
[$ip] = time() +
30 +
intval( rand( 0, 10 ) );
853 $this->_host_dead
[$host] = $this->_host_dead
[$ip];
854 unset( $this->_cache_sock
[$host] );
863 * @param string $key Key to retrieve value for;
865 * @return Resource|bool Resource on success, false on failure
868 function get_sock( $key ) {
869 if ( !$this->_active
) {
873 if ( $this->_single_sock
!== null ) {
874 return $this->sock_to_host( $this->_single_sock
);
877 $hv = is_array( $key ) ?
intval( $key[0] ) : $this->_hashfunc( $key );
878 if ( $this->_buckets
=== null ) {
880 foreach ( $this->_servers
as $v ) {
881 if ( is_array( $v ) ) {
882 for ( $i = 0; $i < $v[1]; $i++
) {
889 $this->_buckets
= $bu;
890 $this->_bucketcount
= count( $bu );
893 $realkey = is_array( $key ) ?
$key[1] : $key;
894 for ( $tries = 0; $tries < 20; $tries++
) {
895 $host = $this->_buckets
[$hv %
$this->_bucketcount
];
896 $sock = $this->sock_to_host( $host );
897 if ( is_resource( $sock ) ) {
900 $hv = $this->_hashfunc( $hv . $realkey );
910 * Creates a hash integer based on the $key
912 * @param string $key Key to hash
914 * @return int Hash value
917 function _hashfunc( $key ) {
918 # Hash function must be in [0,0x7ffffff]
919 # We take the first 31 bits of the MD5 hash, which unlike the hash
920 # function used in a previous version of this client, works
921 return hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
928 * Perform increment/decriment on $key
930 * @param string $cmd Command to perform
931 * @param string|array $key Key to perform it on
932 * @param int $amt Amount to adjust
934 * @return int New value of $key
937 function _incrdecr( $cmd, $key, $amt = 1 ) {
938 if ( !$this->_active
) {
942 $sock = $this->get_sock( $key );
943 if ( !is_resource( $sock ) ) {
947 $key = is_array( $key ) ?
$key[1] : $key;
948 if ( isset( $this->stats
[$cmd] ) ) {
949 $this->stats
[$cmd]++
;
951 $this->stats
[$cmd] = 1;
953 if ( !$this->_fwrite( $sock, "$cmd $key $amt\r\n" ) ) {
957 $line = $this->_fgets( $sock );
959 if ( !preg_match( '/^(\d+)/', $line, $match ) ) {
969 * Load items into $ret from $sock
971 * @param Resource $sock Socket to read from
972 * @param array $ret returned values
973 * @param float $casToken [optional]
974 * @return bool True for success, false for failure
978 function _load_items( $sock, &$ret, &$casToken = null ) {
982 $decl = $this->_fgets( $sock );
984 if ( $decl === false ) {
986 * If nothing can be read, something is wrong because we know exactly when
987 * to stop reading (right after "END") and we return right after that.
990 } elseif ( preg_match( '/^VALUE (\S+) (\d+) (\d+) (\d+)$/', $decl, $match ) ) {
992 * Read all data returned. This can be either one or multiple values.
993 * Save all that data (in an array) to be processed later: we'll first
994 * want to continue reading until "END" before doing anything else,
995 * to make sure that we don't leave our client in a state where it's
996 * output is not yet fully read.
1002 $match[4], // casToken
1003 $this->_fread( $sock, $match[3] +
2 ), // data
1005 } elseif ( $decl == "END" ) {
1006 if ( count( $results ) == 0 ) {
1011 * All data has been read, time to process the data and build
1012 * meaningful return values.
1014 foreach ( $results as $vars ) {
1015 list( $rkey, $flags, $len, $casToken, $data ) = $vars;
1017 if ( $data === false ||
substr( $data, -2 ) !== "\r\n" ) {
1018 $this->_handle_error( $sock,
1019 'line ending missing from data block from $1' );
1022 $data = substr( $data, 0, -2 );
1023 $ret[$rkey] = $data;
1025 if ( $this->_have_zlib
&& $flags & self
::COMPRESSED
) {
1026 $ret[$rkey] = gzuncompress( $ret[$rkey] );
1030 * This unserialize is the exact reason that we only want to
1031 * process data after having read until "END" (instead of doing
1032 * this right away): "unserialize" can trigger outside code:
1033 * in the event that $ret[$rkey] is a serialized object,
1034 * unserializing it will trigger __wakeup() if present. If that
1035 * function attempted to read from memcached (while we did not
1036 * yet read "END"), these 2 calls would collide.
1038 if ( $flags & self
::SERIALIZED
) {
1039 $ret[$rkey] = $this->unserialize( $ret[$rkey] );
1040 } elseif ( $flags & self
::INTVAL
) {
1041 $ret[$rkey] = intval( $ret[$rkey] );
1047 $this->_handle_error( $sock, 'Error parsing response from $1' );
1057 * Performs the requested storage operation to the memcache server
1059 * @param string $cmd Command to perform
1060 * @param string $key Key to act on
1061 * @param mixed $val What we need to store
1062 * @param int $exp (optional) Expiration time. This can be a number of seconds
1063 * to cache for (up to 30 days inclusive). Any timespans of 30 days + 1 second or
1064 * longer must be the timestamp of the time at which the mapping should expire. It
1065 * is safe to use timestamps in all cases, regardless of exipration
1066 * eg: strtotime("+3 hour")
1067 * @param float $casToken [optional]
1072 function _set( $cmd, $key, $val, $exp, $casToken = null ) {
1073 if ( !$this->_active
) {
1077 $sock = $this->get_sock( $key );
1078 if ( !is_resource( $sock ) ) {
1082 if ( isset( $this->stats
[$cmd] ) ) {
1083 $this->stats
[$cmd]++
;
1085 $this->stats
[$cmd] = 1;
1090 if ( is_int( $val ) ) {
1091 $flags |
= self
::INTVAL
;
1092 } elseif ( !is_scalar( $val ) ) {
1093 $val = $this->serialize( $val );
1094 $flags |
= self
::SERIALIZED
;
1095 if ( $this->_debug
) {
1096 $this->_debugprint( sprintf( "client: serializing data as it is not scalar" ) );
1100 $len = strlen( $val );
1102 if ( $this->_have_zlib
&& $this->_compress_enable
1103 && $this->_compress_threshold
&& $len >= $this->_compress_threshold
1105 $c_val = gzcompress( $val, 9 );
1106 $c_len = strlen( $c_val );
1108 if ( $c_len < $len * ( 1 - self
::COMPRESSION_SAVINGS
) ) {
1109 if ( $this->_debug
) {
1110 $this->_debugprint( sprintf( "client: compressing data; was %d bytes is now %d bytes", $len, $c_len ) );
1114 $flags |
= self
::COMPRESSED
;
1118 $command = "$cmd $key $flags $exp $len";
1120 $command .= " $casToken";
1123 if ( !$this->_fwrite( $sock, "$command\r\n$val\r\n" ) ) {
1127 $line = $this->_fgets( $sock );
1129 if ( $this->_debug
) {
1130 $this->_debugprint( sprintf( "%s %s (%s)", $cmd, $key, $line ) );
1132 if ( $line === "STORED" ) {
1134 } elseif ( $line === "NOT_STORED" && $cmd === "set" ) {
1135 // "Not stored" is always used as the mcrouter response with AllAsyncRoute
1143 // {{{ sock_to_host()
1146 * Returns the socket for the host
1148 * @param string $host Host:IP to get socket for
1150 * @return Resource|bool IO Stream or false
1153 function sock_to_host( $host ) {
1154 if ( isset( $this->_cache_sock
[$host] ) ) {
1155 return $this->_cache_sock
[$host];
1160 list( $ip, /* $port */) = explode( ':', $host );
1161 if ( isset( $this->_host_dead
[$host] ) && $this->_host_dead
[$host] > $now ||
1162 isset( $this->_host_dead
[$ip] ) && $this->_host_dead
[$ip] > $now
1167 if ( !$this->_connect_sock( $sock, $host ) ) {
1171 // Do not buffer writes
1172 stream_set_write_buffer( $sock, 0 );
1174 $this->_cache_sock
[$host] = $sock;
1176 return $this->_cache_sock
[$host];
1180 * @param string $text
1182 function _debugprint( $text ) {
1183 $this->_logger
->debug( $text );
1187 * @param string $text
1189 function _error_log( $text ) {
1190 $this->_logger
->error( "Memcached error: $text" );
1194 * Write to a stream. If there is an error, mark the socket dead.
1196 * @param Resource $sock The socket
1197 * @param string $buf The string to write
1198 * @return bool True on success, false on failure
1200 function _fwrite( $sock, $buf ) {
1202 $bufSize = strlen( $buf );
1203 while ( $bytesWritten < $bufSize ) {
1204 $result = fwrite( $sock, $buf );
1205 $data = stream_get_meta_data( $sock );
1206 if ( $data['timed_out'] ) {
1207 $this->_handle_error( $sock, 'timeout writing to $1' );
1210 // Contrary to the documentation, fwrite() returns zero on error in PHP 5.3.
1211 if ( $result === false ||
$result === 0 ) {
1212 $this->_handle_error( $sock, 'error writing to $1' );
1215 $bytesWritten +
= $result;
1222 * Handle an I/O error. Mark the socket dead and log an error.
1224 * @param Resource $sock
1225 * @param string $msg
1227 function _handle_error( $sock, $msg ) {
1228 $peer = stream_socket_get_name( $sock, true /** remote **/ );
1229 if ( strval( $peer ) === '' ) {
1230 $peer = array_search( $sock, $this->_cache_sock
);
1231 if ( $peer === false ) {
1232 $peer = '[unknown host]';
1235 $msg = str_replace( '$1', $peer, $msg );
1236 $this->_error_log( "$msg" );
1237 $this->_dead_sock( $sock );
1241 * Read the specified number of bytes from a stream. If there is an error,
1242 * mark the socket dead.
1244 * @param Resource $sock The socket
1245 * @param int $len The number of bytes to read
1246 * @return string|bool The string on success, false on failure.
1248 function _fread( $sock, $len ) {
1250 while ( $len > 0 ) {
1251 $result = fread( $sock, $len );
1252 $data = stream_get_meta_data( $sock );
1253 if ( $data['timed_out'] ) {
1254 $this->_handle_error( $sock, 'timeout reading from $1' );
1257 if ( $result === false ) {
1258 $this->_handle_error( $sock, 'error reading buffer from $1' );
1261 if ( $result === '' ) {
1262 // This will happen if the remote end of the socket is shut down
1263 $this->_handle_error( $sock, 'unexpected end of file reading from $1' );
1266 $len -= strlen( $result );
1273 * Read a line from a stream. If there is an error, mark the socket dead.
1274 * The \r\n line ending is stripped from the response.
1276 * @param Resource $sock The socket
1277 * @return string|bool The string on success, false on failure
1279 function _fgets( $sock ) {
1280 $result = fgets( $sock );
1281 // fgets() may return a partial line if there is a select timeout after
1282 // a successful recv(), so we have to check for a timeout even if we
1283 // got a string response.
1284 $data = stream_get_meta_data( $sock );
1285 if ( $data['timed_out'] ) {
1286 $this->_handle_error( $sock, 'timeout reading line from $1' );
1289 if ( $result === false ) {
1290 $this->_handle_error( $sock, 'error reading line from $1' );
1293 if ( substr( $result, -2 ) === "\r\n" ) {
1294 $result = substr( $result, 0, -2 );
1295 } elseif ( substr( $result, -1 ) === "\n" ) {
1296 $result = substr( $result, 0, -1 );
1298 $this->_handle_error( $sock, 'line ending missing in response from $1' );
1305 * Flush the read buffer of a stream
1306 * @param Resource $f
1308 function _flush_read_buffer( $f ) {
1309 if ( !is_resource( $f ) ) {
1315 $n = stream_select( $r, $w, $e, 0, 0 );
1316 while ( $n == 1 && !feof( $f ) ) {
1321 $n = stream_select( $r, $w, $e, 0, 0 );